package kosta.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kosta.model.vo.AdminVO;
import kosta.model.vo.AuctionVO;
import kosta.model.vo.DuplicateItemException;
import kosta.model.vo.ListVO;
import kosta.model.vo.MemberVO;
import kosta.model.vo.MessageVO;
import kosta.model.vo.SearchVO;
import kosta.service.AdminService;
import kosta.service.MemberService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/member")
public class MemberController{
        
        @Resource(name="memberServiceImpl")
        private MemberService memberService;
        @Resource(name="adminServiceImpl")
        private AdminService adminService;   
 
        //@PathVariable 클라이언트 요청 path를 변수로 할당받을 때 사용
        @RequestMapping("/{viewId}View.do")
        public String showView(@PathVariable("viewId") String viewId){
                System.out.println(viewId);
                return viewId+"View.member";
        }
        
        
        @RequestMapping("/findMyId.do")
        public ModelAndView findMyId(MemberVO vo){
                String id=memberService.findMyId(vo);
                return new ModelAndView("findIdResult.member","memberId",id);
        }
        
        @RequestMapping("/findPassword.do")
        public ModelAndView findPassword(MemberVO vo){
                String password=memberService.findMyPassword(vo);
                System.out.println(password);
                return new ModelAndView("findPasswordResult.member","memberPassword",password);
        }

        @RequestMapping("/login.do")
        public ModelAndView adminLogin(HttpServletRequest request,
                HttpServletResponse response,MemberVO vo){
        	HttpSession session=request.getSession(); 
           System.out.println("컨트롤러 admin로그인 vo1값 : "+vo);
           //AdminVO advo=adminService.adminLogin(vo);
           MemberVO mvo=memberService.memberLogin(vo);
           System.out.println("mvo 뭐들어오냐 : "+mvo);
           ModelAndView mv=new ModelAndView("index");
           //회원으로 로그인 못했을 때
           if(mvo==null){
              AdminVO advo=new AdminVO();
              advo.setAdminId(vo.getMemberId());
              advo.setAdminPassword(vo.getMemberPassword());
              AdminVO advo2 = adminService.adminLogin(advo);   
              //관리자 세션 셋
              if(advo2!=null){
            	  session.setAttribute("advo", advo);     
              }                  
           //회원으로 로그인 했을 때 회원 세션 셋
           }else if(mvo!=null&&mvo.getMemberActChk()!=1){                    
             session.setAttribute("mvo", mvo);         
           }
           return mv;
        }
        
        @RequestMapping("/logout.do")
        public ModelAndView logout(HttpServletRequest request,
                        HttpServletResponse response) {
                HttpSession session=request.getSession(false);
                if(session!=null)
                session.invalidate();
                return new ModelAndView("index");
        } 
        /**
         *	pageNo에 해당하는 회원목록을 보여주는 메소드
         * @param pageNo
         * @return
         */
        
        
        //회원가입
        @RequestMapping(value="/memberRegister.do",method=RequestMethod.POST)
        public ModelAndView memberRegister(MemberVO vo) throws UnsupportedEncodingException{
        	     	memberService.registerMember(vo);
        	return new ModelAndView("redirect:registerResult.do?memberId="+vo.getMemberId());
        }
        
        //회원가입 후 정보 보기
        @RequestMapping("/registerResult.do")
    	public ModelAndView registerResult(HttpServletRequest request) {
    		MemberVO vo= memberService.registerResult(request.getParameter("memberId"));
    		return new ModelAndView("memberRegisterResult.member","mvo",vo);
    	}	
        
        //회원정보 수정        
        @RequestMapping(value="/auth_memberUpdate.do",method=RequestMethod.POST)
        public ModelAndView memberUpdate(MemberVO mvo,HttpServletRequest request){
        		memberService.updateMember(mvo);
        		HttpSession session = request.getSession(false);
        		session.setAttribute("mvo", mvo);
        	return new ModelAndView("redirect:auth_memberUpdateResult.do?memberId="+mvo.getMemberId());
        }
        
        //회원정보 수정 후 정보보기
        @RequestMapping("/auth_memberUpdateResult.do")
    	public ModelAndView memberUpdateResult(HttpServletRequest request) {
    		MemberVO mvo= memberService.registerResult(request.getParameter("memberId"));
    		return new ModelAndView("memberUpdateResult.member","mvo",mvo);
    	}	
        

        //중복되는 아이디 있는지 체크
        @RequestMapping("/idDuplCheck.do")
    	@ResponseBody
    	public String idDuplCheck(HttpServletRequest request) {
        	String id = request.getParameter("memberId");
        	System.out.println("idDuplCheck 실행");
        	int adminCount=adminService.adminIdDuplCheck(id);
        	System.out.println("idDuplCheck +"+adminCount);
        	int count=memberService.idDuplCheck(id);
    		String flag="fail";
    		if(count==0&&adminCount==0)
    			flag="ok";
    		return flag;
    	}
        
        //내 입찰내역 조회 하는 메소드
        @RequestMapping("/auth_getMyBidList.do")    
    	public ModelAndView getMyBidList(HttpServletRequest request ,SearchVO svo) {
        	HttpSession session = request.getSession(false);
        	MemberVO mvo = (MemberVO) session.getAttribute("mvo"); 
        	int memberNo = mvo.getMemberNo();
        	System.out.println("세션 멤버넘버 : "+memberNo);       
        	svo.setMemberNo(memberNo);
        	System.out.println("svo : "+svo);
        	ListVO lvo = memberService.getMyBidList(svo);        	
			return new ModelAndView("myBidList.member","lvo",lvo);      						
			
    	}
            
        //내 등록내역 보기
        @RequestMapping("/auth_getMyAuctionRegisterHistory.do")    
       	public ModelAndView getMyAuctionRegisterHistory(HttpServletRequest request, SearchVO svo) {
         	HttpSession session = request.getSession(false);
        	MemberVO mvo = (MemberVO) session.getAttribute("mvo"); 
        	int memberNo = mvo.getMemberNo();
        	System.out.println("세션 멤버넘버 : "+memberNo);       
        	svo.setMemberNo(memberNo);
        	System.out.println("svo : "+svo);
        	ListVO lvo = memberService.getMyAuctionRegisterHistory(svo);        	
			return new ModelAndView("registerHistory.member","lvo",lvo);          	
       	}
        
       

        @RequestMapping("/emailDuplCheck.do")
    	@ResponseBody
    	public String emailDuplCheck(HttpServletRequest request) {
        	String email = request.getParameter("memberEmail");
        	System.out.println("이메일 : "+email);
        	int count=memberService.emailDuplCheck(email);
    		String flag="fail";
    		if(count==0)
    			flag="ok";
    		return flag;
    	}
        
        
        //찜목록에 추가하는 메서드.
        @RequestMapping("/auth_addMyWishList.do")      
        @ResponseBody
      	public AuctionVO addMyWishList(HttpServletRequest request, AuctionVO avo) {   
        	HttpSession session = request.getSession(false);
        	MemberVO mvo = (MemberVO) session.getAttribute("mvo");      
        	System.out.println(avo);     		
        	String title = avo.getBoardTitle().toString();
			try {
				mvo.getWishList().addItem(avo);
			} catch (DuplicateItemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			return avo;
      	}
        
        //찜목록에서 삭제하는 메서드.
        @RequestMapping("/auth_delMyWishList.do") 
        @ResponseBody
      	public AuctionVO delMyWishList(HttpServletRequest request, AuctionVO avo) {   
        	HttpSession session = request.getSession(false);
        	MemberVO mvo = (MemberVO) session.getAttribute("mvo");      
        	System.out.println(avo);     		
        	System.out.println("받는 값들 : "+avo);        	
        	int boardNo = avo.getBoardNo();
			mvo.getWishList().removeItem(boardNo);	
			return avo;
      	}       
        
        //회원정보 수정, 탈퇴시 패스워드 체크하는 메서드
        @RequestMapping("/auth_memberPasswordCheck.do")   
        @ResponseBody
      	public HashMap passwordCheck(HttpServletRequest request) {   
        	HttpSession session = request.getSession(false);
        	MemberVO mvo = (MemberVO) session.getAttribute("mvo");  
        	String command = request.getParameter("command");
        	String memberPassword = request.getParameter("memberPassword");
        	System.out.println("세션 정보 : "+mvo);            	
        	System.out.println("삭제, 수정 여부"+command);     
        	System.out.println("입력한 패스워드 : "+memberPassword);
        	String flag="fail";
        	//비번 맞으면 ok, 틀리면 fail 
        	if(mvo.getMemberPassword().toString().equals(memberPassword.toString())){
        		flag="ok";
        	}        	
        	HashMap map = new HashMap();
        	map.put("flag", flag);
        	map.put("command", command);        	
        	System.out.println(map);
			return map;
      	}
        
        
        //회원탈퇴
        @RequestMapping("/auth_memberLeave.do")    
       	public ModelAndView memberLeave(HttpServletRequest request) {
         	HttpSession session = request.getSession(false);
        	MemberVO mvo = (MemberVO) session.getAttribute("mvo"); 
            System.out.println("세션 멤버넘버 : "+mvo.getMemberNo());  
            int memberNo = mvo.getMemberNo();
        	memberService.memberLeave(mvo);    
        	session.invalidate();
			return new ModelAndView("redirect:/notice/home.do");          	
       	}
        
        @RequestMapping("/sendMessageForm.do")    
       	public ModelAndView sendMessage(HttpServletRequest request, MessageVO vo) {         	
			return new ModelAndView("member/sendMessageForm");          	
       	}
        
        @RequestMapping(value="/sendMessage.do",method=RequestMethod.POST)
        @ResponseBody
       	public String sendMessage(MessageVO msvo) {
        	System.out.println("메세지 테이블에 들어갈 내용 : "+msvo);              
        	memberService.sendMessage(msvo);        
         	return "하하하";
       	}	
        
        //쪽지함 보기(받은쪽지함, 보낸쪽지함은 flag로 구분)
        @RequestMapping("/getMyMessageList.do")    
       	public ModelAndView getMyMessage(HttpServletRequest request,SearchVO svo) {
        	String flag = request.getParameter("flag");        	
         	HttpSession session = request.getSession(false);
        	MemberVO mvo = (MemberVO) session.getAttribute("mvo"); 
        	AdminVO advo = (AdminVO) session.getAttribute("advo"); 
        	System.out.println("flag는? : "+flag);
        	svo.setFlag(flag);
        	if(mvo!=null&&advo==null){
        		svo.setMemberId(mvo.getMemberId());
        	}else if(advo!=null&&mvo==null){
        		svo.setMemberId(advo.getAdminId());
        	}        	
        	System.out.println("svo는?"+svo);
        	ListVO lvo = memberService.getMyMessageList(svo);
        	System.out.println("lvo 뭐 들어오냐 : "+lvo);
         	return new ModelAndView("myMessageList.member","lvo",lvo);
       	}	
        
        //쪽지 상세보기
        @RequestMapping("/showMessageContent.do")    
        public ModelAndView showMessageContent(HttpServletRequest request) {        	
         	HttpSession session = request.getSession(false);              
        	int messageNo = Integer.parseInt(request.getParameter("messageNo"));
        	String flag =request.getParameter("flag");
        	System.out.println("메세지넘버 : "+messageNo);
        	MessageVO msvo = memberService.showMessageContent(messageNo,flag);        
         	return new ModelAndView("showMessageContent.member","msvo",msvo);
       	}	
        
        //쪽지 삭제 메서드(실제 DB에서 삭제되는 것은 보낸사람, 받은사람이 모두 삭제를 눌렀을 때.)
        @RequestMapping("/deleteMessage.do")   
        public ModelAndView deleteMessage(HttpServletRequest request,SearchVO svo) {              	              
        	int messageNo = Integer.parseInt(request.getParameter("messageNo"));
        	String flag =request.getParameter("flag");
        	System.out.println("메세지넘버 : "+messageNo);
        		memberService.deleteMessage(messageNo,flag);         	
         	return new ModelAndView("redirect:getMyMessageList.do?flag="+flag);
       	}	
        
      
        
 
}








     
      
        


